<template>
	<div class="app-container">

		<div class="main-content">
			<div class="filter-panel">
				<h3 class="filter-title">平台筛选</h3>
				<div class="filter-group">
					<div v-for="platform in platformOptions" :key="platform.value"
						:class="['filter-option', { active: filters.platform === platform.value }]"
						@click="handlePlatformFilter(platform.value)">
						<div :class="['platform-color', platform.value]"></div>
						<span>{{ platform.label }}</span>
					</div>
				</div>

				<h3 class="filter-title">用户筛选</h3>
				<div class="filter-group">
					<div v-for="nickname in nicknameOptions" :key="nickname"
						:class="['filter-option', { active: filters.nickname === nickname }]"
						@click="handleNicknameFilter(nickname)">
						<span>{{ nickname }}</span>
					</div>
				</div>
			</div>

			<div class="data-panel">
				<div class="controls">
					<button class="refresh-btn" @click="fetchRecords">
						↻ 刷新数据
					</button>

					<input v-model="filters.keyword" placeholder="输入关键词搜索..."
						style="width: 300px; padding: 10px; border-radius: 4px; border: 1px solid #ddd;"
						@keyup.enter="handleKeywordSearch" />
				</div>

				<div class="table-container">
					<table style="width: 100%; border-collapse: collapse;">
						<thead>
							<tr style="background-color: #f8f9fa;">
								<th style="padding: 12px; text-align: center; width: 120px;">用户昵称</th>
								<th style="padding: 12px; text-align: left; min-width: 300px;">原始URL</th>
								<th style="padding: 12px; text-align: center; width: 100px;">平台</th>
								<th style="padding: 12px; text-align: center; width: 160px;">解析时间</th>
							</tr>
						</thead>
						<tbody>
							<tr v-if="loading">
								<td colspan="6" style="padding: 40px; text-align: center;">
									加载中...
								</td>
							</tr>
							<!-- 错误提示 -->
							<tr v-if="errorMessage">
								<td colspan="4"
									style="color: red; padding: 10px; background: #ffeeee; text-align: center;">
									{{ errorMessage }}
								</td>
							</tr>

							<tr v-else-if="records.length === 0 && !errorMessage">
								<td colspan="4" class="empty-data">
									<div>📄</div>
									<p>暂无解析记录</p>
								</td>
							</tr>
							<!-- 表格行 -->
							<tr v-for="record in records" :key="record.id" style="border-bottom: 1px solid #eee;">
								<td style="padding: 12px; text-align: center;">{{ record.nickname || '未知用户' }}</td>
								<td style="padding: 12px;">
									<span class="url-text" @click="copyUrl(record.original_url)">
										{{ record.original_url || '无URL' }}
									</span>
								</td>
								<td style="padding: 12px; text-align: center;">
									<span :class="['platform-tag', record.platform]" style="color: black;font-size: 15px;">
										{{ getPlatformName(record.platform) || '未知平台' }}
									</span>
								</td>
								<td style="padding: 12px; text-align: center;">
									{{ formatDateTime(record.parse_time) || '未知时间' }}
								</td>
							</tr>
						</tbody>
					</table>

					<!-- 修改分页部分 -->
					<div class="pagination">
						<div style="display: flex; align-items: center; gap: 10px;">
							<span>共 {{ pagination.total }} 条记录</span>
							<select v-model="pagination.pageSize" @change="handleSizeChange(pagination.pageSize)"
								style="padding: 8px; border-radius: 4px; border: 1px solid #ddd;">
								<option value="5">5 条/页</option>
								<option value="10">10 条/页</option>
								<option value="20">20 条/页</option>
								<option value="50">50 条/页</option>
							</select>
							<button @click="handleCurrentChange(pagination.currentPage - 1)"
								:disabled="pagination.currentPage === 1"
								style="padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; background: white;">
								上一页
							</button>
							<span>第 {{ pagination.currentPage }} 页 / 共
								{{ Math.ceil(pagination.total / pagination.pageSize) }} 页</span>
							<button @click="handleCurrentChange(pagination.currentPage + 1)"
								:disabled="pagination.currentPage >= Math.ceil(pagination.total / pagination.pageSize)"
								style="padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; background: white;">
								下一页
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		ref,
		computed,
		onMounted,
		reactive
	} from 'vue';
	import videoParseApi from "../api/videoParseApi.js"
	export default {
		name: 'VideoParseRecordSystem',
		setup() {
			const records = ref([]);
			const loading = ref(false);
			const errorMessage = ref('');
			const nicknameOptions = ref([]);
			const platformOptions = ref([]);

			const filters = reactive({
				platform: '',
				nickname: '',
				keyword: ''
			});

			const pagination = reactive({
				currentPage: 1,
				pageSize: 10,
				total: 0
			});


			const total = computed(() => pagination.total);


			const getPlatformName = (platform) => {
	
				return  platform;
			};

			const formatDateTime = (dateStr) => {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				}).replace(/\//g, '-');
			};

			const copyUrl = (url) => {
				if (!url) return;

				navigator.clipboard.writeText(url).then(() => {
					alert('URL已复制到剪贴板');
				}).catch(err => {
					console.error('复制失败:', err);
					// 降级方案
					const textArea = document.createElement('textarea');
					textArea.value = url;
					document.body.appendChild(textArea);
					textArea.select();
					try {
						document.execCommand('copy');
						alert('URL已复制到剪贴板');
					} catch (err) {
						alert('复制失败');
					}
					document.body.removeChild(textArea);
				});
			};
			console.log('开始获取记录，参数:', {
				nickname: filters.nickname,
				platform: filters.platform,
				keyword: filters.keyword,
				page: pagination.currentPage,
				pageSize: pagination.pageSize
			});

			
		// 修改 updatePlatformOptions 函数
		const updatePlatformOptions = (records) => {
		  const platforms = new Set();
		  records.forEach(record => {
		    if (record.platform && record.platform.trim() !== '') {
		      platforms.add(record.platform);
		    }
		  });
		  
		  
		  
		  // 合并现有的平台选项和新提取的平台
		  const existingPlatforms = new Set(platformOptions.value.map(p => p.value));
		  platforms.forEach(platform => {
			 
		    if (!existingPlatforms.has(platform)) {
		      platformOptions.value.push({
		        value: platform,
		        label: getPlatformName(platform)
		      });
			   
		    }
		  });
		  
		  // 排序
		  platformOptions.value.sort((a, b) => a.label.localeCompare(b.label));

				platformOptions.value = Array.from(platforms).map(platform => ({
					value: platform,
					label: getPlatformName(platform)
				})).sort((a, b) => a.label.localeCompare(b.label));
			};

			const updateNicknameOptions = (records) => {
				const nicknames = new Set();
				records.forEach(record => {
					if (record.nickname && record.nickname.trim() !== '') {
						nicknames.add(record.nickname);
					}
				});
				nicknameOptions.value = Array.from(nicknames).sort();
			};
			// 在 setup() 中修改 fetchRecords 方法
			// fetchRecords 方法
			const fetchRecords = async () => {
				try {
					loading.value = true;
					errorMessage.value = '';
					

					const params = {
						page: pagination.currentPage,
						pageSize: pagination.pageSize
					};

					if (filters.nickname && filters.nickname.trim() !== '') {
						params.nickname = filters.nickname;
					}
					if (filters.platform && filters.platform.trim() !== '') {
						params.platform = filters.platform;
					}
					if (filters.keyword && filters.keyword.trim() !== '') {
						params.keyword = filters.keyword;
					}

					const response = await videoParseApi.getAllRecords(params);
					console.log(response.data.data.records);

					if (response.data) {
						// 根据实际响应结构调整
						const responseData = response.data.data || response.data;
						const recordsData = responseData.records || [];
						const totalData = responseData.total || 0;

						records.value = recordsData;
						pagination.total = totalData;

						// 更新用户昵称选项
						updateNicknameOptions(recordsData);
						updatePlatformOptions(recordsData);
					}
				} catch (error) {
					console.error('获取数据失败:', error);
					errorMessage.value = error.message;
					records.value = [];
					pagination.total = 0;
				} finally {
					loading.value = false;
				}
			};


			// 修改筛选处理函数
			const handlePlatformFilter = (platform) => {
				filters.platform = filters.platform === platform ? '' : platform;
				pagination.currentPage = 1;
				fetchRecords();
			};

			const handleNicknameFilter = (nickname) => {
				filters.nickname = filters.nickname === nickname ? '' : nickname;
				pagination.currentPage = 1;
				fetchRecords();
			};

			const handleKeywordSearch = () => {
				pagination.currentPage = 1;
				fetchRecords();
			};

			// 添加清除关键词的功能
			const handleKeywordClear = () => {
				filters.keyword = '';
				pagination.currentPage = 1;
				fetchRecords();
			};


			const handleSizeChange = (size) => {
				pagination.pageSize = size;
				pagination.currentPage = 1;
				fetchRecords();
			};

			const handleCurrentChange = (page) => {
				if (page < 1) return;
				const totalPages = Math.ceil(pagination.total / pagination.pageSize);
				if (page > totalPages) return;

				pagination.currentPage = page;
				fetchRecords();
			};

			onMounted(() => {
				fetchRecords();
				
			});

			return {
				records,
				loading,
				errorMessage,
				filters,
				pagination,
				platformOptions,
				nicknameOptions,
				total,
				getPlatformName,
				formatDateTime,
				copyUrl,
				fetchRecords,
				handlePlatformFilter,
				handleNicknameFilter,
				handleKeywordSearch,
				handleKeywordClear,
				handleSizeChange,
				handleCurrentChange
			};
		}
	}
</script>

<style scoped>
	* {
	            margin: 0;
	            padding: 0;
	            box-sizing: border-box;
	            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
	        }
	
	        body {
	            background-color: #f5f7fa;
	            padding: 20px;
	        }
	
	        .app-container {
	            max-width: 1200px;
	            margin: 0 auto;
	        }
	
	        .header {
	            text-align: center;
	            margin-bottom: 30px;
	            padding: 25px;
	            background: linear-gradient(90deg, #3498db, #2c3e50);
	            color: white;
	            border-radius: 10px;
	            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
	        }
	
	        .header h1 {
	            font-size: 2.5rem;
	            margin-bottom: 10px;
	        }
	
	        .header p {
	            font-size: 1.2rem;
	            opacity: 0.9;
	        }
	
	        .main-content {
	            display: grid;
	            grid-template-columns: 280px 1fr;
	            gap: 20px;
	        }
	
	        /* 筛选面板样式调整 - 向左对齐 */
	        .filter-panel {
	            background: white;
	            padding: 20px 15px 20px 10px; /* 减少右侧内边距，增加左侧内边距 */
	            border-radius: 10px;
	            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
	            height: fit-content;
	        }
	
	        .filter-title {
	            font-size: 1.2rem;
	            margin-bottom: 15px;
	            padding-bottom: 10px;
	            border-bottom: 2px solid #3498db;
	            color: #2c3e50;
	            /* 向左对齐调整 */
	            padding-left: 5px;
	            margin-left: 0;
	            text-align: left;
	        }
	
	        .filter-group {
	            margin-bottom: 25px;
	            /* 向左对齐调整 */
	            padding-left: 5px;
	            margin-left: 0;
	        }
	
	        .filter-option {
	            display: flex;
	            align-items: center;
	            padding: 8px 10px 8px 8px; /* 调整内边距，左侧减少 */
	            margin: 5px 0;
	            border-radius: 5px;
	            cursor: pointer;
	            transition: all 0.3s;
	            /* 向左对齐调整 */
	            margin-left: 0;
	            justify-content: flex-start;
	        }
	
	        .filter-option:hover {
	            background-color: #f5f7fa;
	        }
	
	        .filter-option.active {
	            background-color: #3498db;
	            color: white;
	        }
	
	        .platform-color {
	            width: 16px;
	            height: 16px;
	            border-radius: 50%;
	            margin-right: 8px; /* 减少右边距 */
	        }
	
	        .data-panel {
	            background: white;
	            padding: 20px;
	            border-radius: 10px;
	            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
	        }
	
	        .controls {
	            display: flex;
	            justify-content: space-between;
	            margin-bottom: 20px;
	            align-items: center;
	        }
	
	        .table-container {
	            margin-top: 20px;
	        }
	
	        table {
	            width: 100%;
	            border-collapse: collapse;
	        }
	
	        th {
	            padding: 12px;
	            text-align: center;
	            background-color: #f8f9fa;
	        }
	
	        .col-nickname {
	            width: 120px;
	        }
	
	        .col-url {
	            text-align: left;
	            min-width: 300px;
	        }
	
	        .col-platform {
	            width: 100px;
	        }
	
	        .col-time {
	            width: 160px;
	        }
	
	        td {
	            padding: 12px;
	            border-bottom: 1px solid #eee;
	        }
	
	        .url-text {
	            word-break: break-all;
	            color: #3498db;
	            cursor: pointer;
	        }
	
	        .url-text:hover {
	            text-decoration: underline;
	        }
	
	        .loading-cell, .error-cell, .empty-data {
	            text-align: center;
	            padding: 40px;
	        }
	
	        .error-cell {
	            color: red;
	            background: #ffeeee;
	        }
	
	        .empty-data {
	            color: #909399;
	            font-size: 16px;
	        }
	
	        .platform-tag {
	            padding: 5px 12px;
	            border-radius: 15px;
	            font-size: 12px;
	            color: white;
	            text-align: center;
	            display: inline-block;
	        }
	
	        .pagination {
	            display: flex;
	            justify-content: center;
	            margin-top: 20px;
	        }
	
	        .pagination-controls {
	            display: flex;
	            align-items: center;
	            gap: 10px;
	        }
	
	        .refresh-btn {
	            background: linear-gradient(135deg, #3498db, #2c3e50);
	            border: none;
	            color: white;
	            padding: 12px 24px;
	            border-radius: 5px;
	            cursor: pointer;
	            display: flex;
	            align-items: center;
	            gap: 8px;
	            font-weight: bold;
	            transition: all 0.3s;
	        }
	
	        .refresh-btn:hover {
	            transform: translateY(-2px);
	            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
	        }
	
	        .search-input {
	            width: 300px;
	            padding: 10px;
	            border-radius: 4px;
	            border: 1px solid #ddd;
	        }
	
	        .page-size-select, .pagination-btn {
	            padding: 8px 12px;
	            border-radius: 4px;
	            border: 1px solid #ddd;
	            background: white;
	        }
	
	        /* 平台颜色标识 */
	        .douyin {
	            background-color: #FE2C55;
	        }
	
	        .kuaishou {
	            background-color: #FFC300;
	        }
	
	        .bilibili {
	            background-color: #FB7299;
	        }
	
	        .xiaohongshu {
	            background-color: #FF2442;
	        }
	
	        .weibo {
	            background-color: #FF8200;
	        }
	
	        .other {
	            background-color: #909399;
	        }
	
	        /* 平台标签样式 */
	        .platform-tag.douyin {
	            background-color: #FE2C55;
	        }
	
	        .platform-tag.kuaishou {
	            background-color: #FFC300;
	        }
	
	        .platform-tag.bilibili {
	            background-color: #FB7299;
	        }
	
	        .platform-tag.xiaohongshu {
	            background-color: #FF2442;
	        }
	
	        .platform-tag.weibo {
	            background-color: #FF8200;
	        }
	
	        .platform-tag.other {
	            background-color: #909399;
	        }
	
	        /* 响应式设计 */
	        @media (max-width: 992px) {
	            .main-content {
	                grid-template-columns: 1fr;
	            }
	
	            .filter-panel {
	                order: 2;
	            }
	
	            .data-panel {
	                order: 1;
	            }
	
	            .header h1 {
	                font-size: 2rem;
	            }
	
	            .header p {
	                font-size: 1rem;
	            }
	        }
	
	        @media (max-width: 768px) {
	            .app-container {
	                padding: 10px;
	            }
	
	            .controls {
	                flex-direction: column;
	                gap: 15px;
	                align-items: stretch;
	            }
	
	            .filter-group {
	                display: grid;
	                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
	                gap: 10px;
	            }
	        }
</style>